package com.example.helloandroidworld;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;

import com.actionbarsherlock.app.SherlockFragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler; 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SchedulerFragment extends SherlockFragment
{
	// easy stuff
	Calendar today;
	TextView MonthName;
	Button prev, next, buttonDay, buttonMonth, buttonYear, buttonView, buttonAddEvent;
	ArrayList<String> items;
	
	// all itme associated with the grid
	GridView grid;
	SchedulerAdapter schedulerAdapter;
	Handler handler;
	
	@Override
	public void onCreate( Bundle saveInstanceState)
	{
		super.onCreate(saveInstanceState);
		if( saveInstanceState != null )
		{
			today = Calendar.getInstance();// getInstance is a constructor for today
	    	today.set(saveInstanceState.getInt("Year", today.get(Calendar.YEAR)),
	    			saveInstanceState.getInt("Month", today.get(Calendar.MONTH)),
	    			saveInstanceState.getInt("Day", today.get(Calendar.DAY_OF_MONTH)));
	    	}
		else
		{
			today = Calendar.getInstance();
		}
	}
		
	@Override
	public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
	{ 	
		View view =  inflater.inflate( R.layout.schedulerfragment, container, false );
		items = new ArrayList<String>();
		setUpGrid1(view); // isolating grid logic for better comments
		setUpButtons(view);
		return view;
	}
	
	@Override
	public void onActivityCreated( Bundle savedInstanceState )
	{
		super.onActivityCreated(savedInstanceState);
		MonthName.setText(android.text.format.DateFormat.format("MMMM dd, yyyy", today));
		setUpGrid2();
	}
	
    @Override
    public void onSaveInstanceState( Bundle saveInstanceState)
    {
    	super.onSaveInstanceState(saveInstanceState);
    	saveInstanceState.putInt("Day", today.get(Calendar.DAY_OF_MONTH));
    	saveInstanceState.putInt("Month", today.get(Calendar.MONTH));
    	saveInstanceState.putInt("Year", today.get(Calendar.YEAR));
    }
	
		private void setUpButtons(View v)
	{   
		prev = (Button) v.findViewById(R.id.calPrev);
		next = (Button) v.findViewById(R.id.calNext);
		MonthName = (TextView) v.findViewById(R.id.calMonthName);
		/// set up buttons
		buttonDay = (Button) v.findViewById(R.id.scheduDay);
		buttonYear = (Button) v.findViewById(R.id.schedulerYear);
		buttonMonth = (Button) v.findViewById(R.id.schedulerMonth);
		buttonView = (Button) v.findViewById(R.id.schedulerView);
		buttonAddEvent = (Button) v.findViewById(R.id.addStuff);

				
				// add functionality
				buttonView.setOnClickListener(new View.OnClickListener() {
				
					@Override
					public void onClick(View v) 
					{
						if( buttonMonth.getVisibility() == View.VISIBLE)
						{
							buttonDay.setVisibility(View.INVISIBLE);
							buttonMonth.setVisibility(View.INVISIBLE);
							buttonYear.setVisibility(View.INVISIBLE);					
						}
						else
						{
							buttonDay.setVisibility(View.VISIBLE);
							buttonMonth.setVisibility(View.VISIBLE);
							buttonYear.setVisibility(View.VISIBLE);
						}
					}});
				
				buttonAddEvent.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
					}});
		
		handler = new Handler();
		handler.post( Updater );
		
		prev.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// decrement month counter
				if( today.getActualMinimum(Calendar.MONTH) == today.get(Calendar.MONTH)) // decrement year, set month to December
				{
					today.set((today.get(Calendar.YEAR)-1), today.getActualMaximum(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
					
				}
				else // else decrement month only
				{
					today.set((today.get(Calendar.YEAR)), (today.get(Calendar.MONTH)-1), today.get(Calendar.DAY_OF_MONTH));
				}
				buttonsTitleBar();
			}});
		
		next.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//increment month counter
				if( today.getActualMaximum(Calendar.MONTH) == today.get(Calendar.MONTH) ) // increment year and set month to january
				{
					today.set((today.get(Calendar.YEAR)+1), today.getActualMinimum(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
				}
				else // increment month
				{
					today.set((today.get(Calendar.YEAR)), (today.get(Calendar.MONTH)+1), today.get(Calendar.DAY_OF_MONTH));
				}
				buttonsTitleBar();
			}});
	}
	
	private void buttonsTitleBar()
	{
		MonthName.setText(android.text.format.DateFormat.format("MMMM dd, yyyy", today));
		schedulerAdapter.setUp();
		schedulerAdapter.notifyDataSetChanged();
	}

	// calendar set starts here *********************
	private void setUpGrid1(View v)
	{
		grid = (GridView) v.findViewById(R.id.myCal);				
		// the adapter actually handles the process of creating the calendar
		// gridview simply provides the layout for it
		grid.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
			{
				// TODO Auto-generated method stub
				//Toast.makeText(getActivity(), "Please enter both phone number and message.", Toast.LENGTH_SHORT).show();
			}});
	}
	
	private void setUpGrid2()
	{
		schedulerAdapter = new SchedulerAdapter(getActivity(), today ); // creates data
		grid.setAdapter(schedulerAdapter);					// loads data into calendar and adapter associated
		
	}
	
	// calendar functions and adapter class **************************
	private static class SchedulerAdapter extends BaseAdapter  
	{
		public int id;
		public String[] datesInTheMonth; // contains all the days to create in the Grid 
									// populated in set-up
									// the array size will be used to determine how many grids to draw
		
		/*		The logic flows like this. Call the constructor. Constructor calls setUp to create the dates. 
		 * 		Then getView is called to create each cell. it uses the date info to create all the necessary cells
		 * 
		 */
		private Context returnsInflater; // you need the context from the fragment to inflate
		Calendar dayReference, Today, junk;     // the views in the grid. 
		ArrayList<String> items;
		
		public SchedulerAdapter(Context inflateEasy, Calendar date)
		{
			id = 0;
			returnsInflater = inflateEasy;// Calendar is passed by reference
			Today = date; // clone creates an exact copy
			this.items = new ArrayList<String>();
	        setUp(); // creates all the dates that go into the calendar
		}
		
		public void setUp() // creates the cells that go in the grid
		{					// or all the dates in the calendar month view
			dayReference = (Calendar)Today.clone();
			junk = (Calendar)dayReference.clone();
			items.clear();
			// current month
			// Calculator the first day string (ie Monday ) and last day int (30, 31) in the current month
			junk.set(Calendar.DAY_OF_MONTH, 0);// first day of month
			int firstDayStringInMonth = junk.get(Calendar.DAY_OF_WEEK); // the first day of the month ie Tuesday
			int lastDayIntInMonth = (dayReference.getActualMaximum(Calendar.DAY_OF_MONTH)); // last day of the month
			
			
			// calculate  the last day of the prior month
			int lastDayIntInPriorMonth; // variable will be used later
			int PriorMonthStartPrint;
			// the case if the current month is january.
			// decrement month 
			// decrement year
			if(firstDayStringInMonth == 0)
			{
				lastDayIntInPriorMonth = 7;
			}
			if( dayReference.get(Calendar.MONTH) == dayReference.getActualMinimum(Calendar.MONTH) )
			{ // Month is January
				// have to decrement the month and year
				junk = (Calendar) dayReference.clone();
				junk.set(Calendar.MONTH, (dayReference.get(Calendar.MONTH)-1));
				junk.set(Calendar.YEAR, (dayReference.get(Calendar.YEAR)-1));
				lastDayIntInPriorMonth =junk.getActualMaximum(Calendar.DAY_OF_MONTH); // last day of the prior month
			}else
			{// any other month
				junk = (Calendar) dayReference.clone(); // this is the problem
				junk.set(Calendar.MONTH, (dayReference.get(Calendar.MONTH)-1));
				lastDayIntInPriorMonth =junk.getActualMaximum(Calendar.DAY_OF_MONTH);
			}
			
			if(firstDayStringInMonth == 0 )
			{
				PriorMonthStartPrint = lastDayIntInPriorMonth - firstDayStringInMonth;
			}
			else
			{
				PriorMonthStartPrint = lastDayIntInPriorMonth - firstDayStringInMonth +1;
			}
			
			
			datesInTheMonth = new String[42];
			int index = 0;
			//print prior days
			while( PriorMonthStartPrint <= lastDayIntInPriorMonth)
			{
				datesInTheMonth[index] = ""+PriorMonthStartPrint;
				PriorMonthStartPrint++;
				index++;
			}
			// print current month days
			lastDayIntInMonth = lastDayIntInMonth+index;
			for( int i =1; index < lastDayIntInMonth; i++)
			{
				datesInTheMonth[index] = ""+i;
				index++;
			}
			// print remainder of days
			for( int i =1; index < 42; i++)
			{
				datesInTheMonth[index] = ""+i;
				index++;
			}
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)  // creates the cells
		{
		//	Toast.makeText(returnsInflater, "getView", Toast.LENGTH_SHORT).show();
			LinearLayout cellView = (LinearLayout) convertView;
			if (convertView == null)  /// if view exists, reuse the container
			{ 
				cellView =  (LinearLayout) ((LayoutInflater) returnsInflater.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.calendarcell, null);
			}
			
			if(position < 7 )
			{
				if( Integer.parseInt(datesInTheMonth[position]) >6 )
				{
					cellView.findViewById(R.id.calendarCellBackground).setBackgroundResource(R.color.dullMap);	
				}
				else
				{
					cellView.findViewById(R.id.calendarCellBackground).setBackgroundResource(R.color.whiter);
				}
			}
			else if(position> 28 )
			{

				if( Integer.parseInt(datesInTheMonth[position]) <20  )
	 			{
					cellView.findViewById(R.id.calendarCellBackground).setBackgroundResource(R.color.dullMap);	
				}
				else
				{
					cellView.findViewById(R.id.calendarCellBackground).setBackgroundResource(R.color.whiter);
				}
			}
			
			int firstDayStringInMonth = dayReference.get(Calendar.DAY_OF_WEEK); // the first day of the month ie Tuesday
			TextView calendarCell = (TextView) cellView.findViewById(R.id.calendarCell);
			calendarCell.setText(datesInTheMonth[position]);
			return cellView;
		}
		
		@Override
		public int getCount() 
		{	// base adapter draws this many grids
			return datesInTheMonth.length; 
		}

		@Override
		public Object getItem(int position) {/* done*/return null;}

		@Override
		public long getItemId(int position) {/*done*/return 0;}



		public void setItems(ArrayList<String> items2) {
	    /*	for(int i = 0;i != items2.size();i++)
	    	{
	    		if(items2.get(i).length()==1) 
	    		{
	    			items2.set(i, "0" + items2.get(i));
	    		}
	    	}
	    	
	    	items = items2;*/
		}		
	}
	
	
	
	private void Refresh()
	{

		schedulerAdapter.setUp();
		schedulerAdapter.notifyDataSetChanged();				
		handler.post(Updater); 			
		MonthName.setText(android.text.format.DateFormat.format("MMMM dd, yyyy", today));
		
	}
	
	//loads items into the calendar ----------
	private Runnable Updater = new Runnable()  //test
	{	@Override
		public void run() 
		{
				items.clear(); // populates dates with events things to have in it
				// format random values. You can implement a dedicated class to provide real values
				for(int i=0;i<31;i++) {
					Random r = new Random();
					
					if(r.nextInt(10)>6)
					{
						items.add(Integer.toString(i));
					}
				}
		
				schedulerAdapter.setItems(items);
		 		schedulerAdapter.notifyDataSetChanged();
			
		}};
		
		/*
		public void onNewIntent(Intent intent) 
		{
			String date = intent.getStringExtra("date");
			String[] dateArr = date.split("-"); // date format is yyyy-mm-dd
			month.set(Integer.parseInt(dateArr[0]), Integer.parseInt(dateArr[1]), Integer.parseInt(dateArr[2]));
		}*/
		
}